package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 产生Project通过Ajax方法调用URL：ajax_create_project<br>
 * 必须登陆：true<br>
 * 必须管理：true<br>
 * 参数：<br>
 * columns_id，必须，产生的Project的分类栏目<br>
 * isoriginal，必须，是否为原创<br>
 * isCreateApp，必须，是否可以DIY产生App<br>
 * title，必须，Project的标题<br>
 * image_filename，必须，Project封面图片名<br>
 * context，必须，Project内容<br>
 * iframe_url，必须，非原创为框架URL，原创为Apps文件夹名<br>
 * original_url，非必须，转载内容的原网址<br>
 * 注：projectId和appId必须有一个<br>
 * @author fc
 */
public class AjaxCreateProject extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		Connection connection = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			if (loginUser != null && loginUser.isAdmin()) {
				byte columns_id = Byte.parseByte(req.getParameter("columns_id"));
				boolean isoriginal = Integer.parseInt(req.getParameter("isoriginal")) != 0;
				boolean isCreateApp = Integer.parseInt(req.getParameter("isCreateApp")) != 0;
				String title = req.getParameter("title");
				String image_filename = req.getParameter("image_filename");
				String context = req.getParameter("context");
				String iframe_url = req.getParameter("iframe_url");
				String original_url = req.getParameter("original_url");
				connection = config.getConn();
				CommonQuery.insert_project(connection, columns_id, isoriginal, title, image_filename, context,
						iframe_url, original_url,isCreateApp);
				json.put("type", 0);
			} else {
				json.put("type", -1);
				json.put("msg", "没有管理员权限");
			}
		} catch (SQLException e) {
			json.put("type", -2);
			json.put("msg", "数据库错误");
			e.printStackTrace();
		} catch (Exception e) {
			json.put("type", -3);
			json.put("msg", "未知错误");
			e.printStackTrace();
			Logger.getRootLogger().error(e);
		}finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		resp.getWriter().println(json);
	}
}
